package com.amigo.online.consumer.merchant.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.amigo.online.common.base.controller.BaseConsumerController;
import com.amigo.online.common.core.response.Meta;
import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.dto.goods.AroundGoodsDto;
import com.amigo.online.common.param.dto.goods.GoodsEditDto;
import com.amigo.online.common.param.dto.goods.GoodsManagerDto;
import com.amigo.online.common.util.CommonValidator;
import com.amigo.online.common.util.UploadTempUtil;
import com.amigo.online.consumer.merchant.exception.GoodsException;
import com.amigo.online.consumer.merchant.service.FileUploadService;
import com.amigo.online.consumer.merchant.service.GoodsService;
import com.amigo.online.consumer.merchant.util.UploadImgUtil;
import com.google.gson.Gson;

/**
 * <code>MerchantCustomerController.java</code>
 * <p>
 *
 * </p>
 * <p>
 * 
 * @company Amigo
 * @author LuChen
 * @time 2018年12月17日 下午5:13:32
 * @version 1.0
 * @lastUpdate 无
 *             </p>
 */
@RestController
@RequestMapping(value = "/goods", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class GoodsController extends BaseConsumerController {

	@Autowired
	private GoodsService goodsService;

	@Autowired
	FileUploadService fileUploadService;

	/**
	 * 首页搜索接口
	 * 
	 * @param
	 * @return
	 */
	@PostMapping("/search")
	public ResponseEntity<Response> findAroundPeople(@RequestBody AroundGoodsDto aroundGoodsDto) {
		return goodsService.findAroundGoods(aroundGoodsDto);
	}

	/**
	 * 首页搜索接口
	 * 
	 * @param
	 * @return
	 */
	@PostMapping("/v2/search")
	public ResponseEntity<Response> findAroundPeopleV2(@RequestBody AroundGoodsDto aroundGoodsDto) {
		return goodsService.findAroundPeopleV2(aroundGoodsDto);
	}

	
	
	/**
	 * 获得商品详情
	 *
	 * @return
	 */
	@GetMapping("/goodsDetail/{goodsId}")
	public ResponseEntity<Response> getgoodsDetail(@PathVariable Long goodsId) {
		return goodsService.getgoodsDetail(goodsId);
	}

	/**
	 * 获取商品信息（根据不同字段排序）
	 * 
	 * @param merchantId
	 *            商户id
	 * @param page
	 *            页码
	 * @param size
	 *            每页数量
	 * @param type
	 *            查询类别 ,1热门 2推荐 3好评率
	 * @return
	 */
	@GetMapping("/merchantGoods")
	public ResponseEntity<Response> getMerchantGoods(@RequestParam("merchantId") Long merchantId,
			@RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestParam("type") Integer type,
			@RequestParam(name = "categoryId", required = false) Long categoryId) {
		return goodsService.getGoodsOrderBYField(merchantId, page, size, type, categoryId);
	}

	@PostMapping("/shelf")
	public ResponseEntity<Response> shelfMerchantGoods(@RequestBody GoodsManagerDto goodsManagerDto) {
		if (!CommonValidator.validate(goodsManagerDto)) {
			throw new GoodsException(StatusCode.BAD_REQUEST);
		}
		return goodsService.shelfMerchantGoodsByGoodsId(goodsManagerDto);
	}

	@PostMapping("/obtained")
	public ResponseEntity<Response> obtainedMerchantGoods(@RequestBody GoodsManagerDto goodsManagerDto) {
		if (!CommonValidator.validate(goodsManagerDto)) {
			throw new GoodsException(StatusCode.BAD_REQUEST);
		}
		return goodsService.obtainedMerchantGoodsByGoodsId(goodsManagerDto);
	}

	@PostMapping("/delete")
	public ResponseEntity<Response> deleteMerchantGoods(@RequestBody GoodsManagerDto goodsManagerDto) {
		if (!CommonValidator.validate(goodsManagerDto)) {
			throw new GoodsException(StatusCode.BAD_REQUEST);
		}
		return goodsService.deleteMerchantGoodsByGoodsId(goodsManagerDto);
	}

	@PostMapping("/edit")
	public ResponseEntity<Response> editMerchantGoods(@RequestBody GoodsEditDto goodsEditDto) {
		if (!CommonValidator.validate(goodsEditDto)) {
			throw new GoodsException(StatusCode.BAD_REQUEST);
		}
		return goodsService.editMerchantGoods(goodsEditDto);
	}

	@PostMapping("/new")
	public ResponseEntity<Response> newMerchantGoods(@RequestBody GoodsEditDto goodsEditDto) {
		if (!CommonValidator.validate(goodsEditDto)) {
			throw new GoodsException(StatusCode.BAD_REQUEST);
		}
		return goodsService.newMerchantGoods(goodsEditDto);
	}

	@PostMapping("/upload/img")
	public ResponseEntity<Response> uploadVideoFile(@RequestPart(value = "files") MultipartFile[] files, HttpServletRequest request) throws ClientProtocolException, IOException {
//		List<String> resultList = fileUploadService.handleMultiFileUploadList(files);
//		return success(resultList);
		System.out.println("开始上传");
		String token = request.getHeader("ACCESS_TOKEN");
		System.out.println("ACCESS_TOKEN：" + token);
		List<String> address = new ArrayList<>();
		for (MultipartFile file : files) {
			System.out.println("ContentType = " + file.getContentType());
			String originalFilename = file.getOriginalFilename();
			System.out.println("originalFilename = " + originalFilename);
			String result = "";
			if (originalFilename != null && originalFilename.contains("mp4")) {
				result = UploadTempUtil.uploadResourceVideo(file, token);
				System.out.println("video_result = " + result);
			}else {
				result = UploadTempUtil.uploadResourceImg(file, token);
				System.out.println("img_result = " + result);
			}
			Response parseObject = new Gson().fromJson(result, Response.class);
			if(((Meta)parseObject.getMeta()).getCode() == 401) {
				return failure(StatusCode.UNAUTHORIZED); 
			}
			address.add(getAddress(parseObject));
		}
		return success(address);
	}
	private String getAddress(Response parseObject) {
		String address = "";
		if (parseObject != null && parseObject.getData() != null) {
			Object data = parseObject.getData();
			if (data instanceof List) {
				List<String> addressList = (List<String>) data;
				address = addressList.get(0);
			}
		}
		return address;
	}

	@PostMapping("/upload/video")
	public ResponseEntity<Response> uploadImgFile(@RequestPart(value = "files") MultipartFile[] files) {
		List<String> resultList = fileUploadService.handleMultiFileUploadList(files);
		return success(resultList);
	}

	@PostMapping("/upload/img/futuretask")
	public ResponseEntity<Response> uploadVideoFileList(@RequestPart(value = "files") MultipartFile[] files) {
		List<String> resultMap = fileUploadService.handleMultiFileUploadList(files);
		return success(resultMap);
	}

	@PostMapping("/upload/img/future")
	public ResponseEntity<Response> uploadFileList(@RequestPart(value = "files") MultipartFile[] files) {
		long time = System.currentTimeMillis();
		List<String> resultMap = fileUploadService.handleFileUploadList(files);
		System.out.println(System.currentTimeMillis() - time);
		return success(resultMap);
	}

	@PostMapping("/upload/img/orginal")
	public ResponseEntity<Response> uploadFile(@RequestPart(value = "files") MultipartFile[] files) {
		long time = System.currentTimeMillis();
		List<String> resultMap = UploadImgUtil.uploadImg(files);
		System.out.println(System.currentTimeMillis() - time);
		return success(resultMap);
	}
	

}
